package com.x25175.file.service;

import com.x25175.file.entity.Picture;
import com.x25175.file.mapper.PictureMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author 徐佳辉
 * @date 2020/11/27 11:59
 */
@Service
@Slf4j
public class PictureService {
    @Autowired
    private PictureMapper pictureMapper;
    @Value("${pictureurl}")
    private String localurl;

    public List<Picture> list() {
        List<Picture> list = pictureMapper.list();
        return list;
    }


    public boolean delete(Integer pId) {
        if (pId == null) {
            return false;
        }
        int delete = pictureMapper.delete(pId);
        return delete > 0;
    }

    public boolean insert(Picture picture) {
        int insert = pictureMapper.insert(picture);
        return insert > 0;
    }

    /**
     * 属性不为空插入 但是结果和直接插入没区别
     *
     * @param picture
     * @return
     */
    public boolean insertDynamic(Picture picture) {
        int i = pictureMapper.insertDynamic(picture);
        return i > 0;
    }

    /**
     * 根据主键更新跳过null属性
     *
     * @param picture
     * @return
     */
    public boolean updateDynamic(Picture picture) {
        int i = pictureMapper.updateDynamic(picture);
        return i > 0;
    }

    /**
     * 根据主键更新其他所有字段
     *
     * @param picture
     * @return
     */
    public boolean update(Picture picture) {
        int update = pictureMapper.update(picture);
        return update > 0;
    }

    public Picture selectByPId(Integer pId) {
        Picture picture = pictureMapper.selectByPId(pId);
        return picture;
    }

    public int deleteByPictureList(List<Picture> pictures) {
        int i = pictureMapper.deleteByPictureList(pictures);
        return i;
    }

    /**
     * 根据数据库的图片地址删除对应图片文件
     *
     * @param url
     * @return
     */
    public boolean deleteImgByDataUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return false;
        }
        log.info(url);
        String s = url.replaceFirst("/img/", localurl);
        log.info(s);
        File file = new File(s);
        boolean delete = file.delete();
        return delete;
    }


}
